package spring.boot.wx.mini.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import spring.boot.wx.mini.mapper.WxMiniMapper;
import spring.boot.wx.mini.model.WxMini;

import java.util.List;

@Slf4j
@Service
public class WxMiniService extends ServiceImpl<WxMiniMapper, WxMini> {

    @Value("${wx-mini.get-access-token-url}")
    private String getAccessTokenUrl;

    @Autowired
    private RestTemplate restTemplate;

    public Long getExpiresByAppId(String appId) {
        QueryWrapper<WxMini> wrapper = new QueryWrapper<>();
        wrapper.eq("app_id", appId);
        List<WxMini> list = list(wrapper);
        if (list != null && list.size() > 0) {
            return list.get(0).getExpires();
        }
        return null;
    }

    public boolean updateAccessTokenByAppId(String appId, String accessToken, Long expire) {
        UpdateWrapper<WxMini> wrapper = new UpdateWrapper<>();
        wrapper.set("access_token", accessToken);
        wrapper.set("expires", expire);
        wrapper.eq("app_id", appId);
        return update(wrapper);
    }


    /**
     * 初始化access token
     */
    public boolean setAccessToken(String appId, String appSecret) {
        Long expires = getExpiresByAppId(appId);
        if (expires != null && expires > System.currentTimeMillis()) {
            log.info("access_token 还未过期！appId={}", appId);
            return true;
        }
        log.info("access_token 已经过期！appId={}", appId);

        String url = getAccessTokenUrl.replace("APP_ID", appId).replace("APP_SECRET", appSecret);
        JSONObject accessTokenJson = null;
        try {
            accessTokenJson = restTemplate.getForObject(url, JSONObject.class);
        } catch (RestClientException e) {
            log.error("获取 accessTokenObject异常！appId=[{}]", appId);
            log.error(e.getMessage(), e);
            return false;
        }

        String accessToken = accessTokenJson.getString("access_token");
        if (accessToken != null && accessToken.trim().length() > 0) {
            log.info("获取access_token 成功!  msg={}", accessTokenJson.toJSONString());
            long expire = accessTokenJson.getLong("expires_in");
            return updateAccessTokenByAppId(appId, accessToken, expire * 1000 + System.currentTimeMillis());
        } else {
            String errCode = accessTokenJson.getString("errcode");
            String errMsg = accessTokenJson.getString("errmsg");
            log.error("获取access_token 失败! err_code={}     err_msg={}", errCode, errMsg);
            return false;
        }
    }
}
